package com.shy.web.controller;

import java.net.URL;
import java.nio.charset.Charset;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shy.base.controller.AbsController;
import com.shy.base.vo.AppConstants;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("commonApi")
public class BindController extends AbsController{
	
	/**
	 * var t = "http://122.114.89.46:9999/shycms/front/3/pc";
if (from.indexOf("/chapter/") >= 0) {
   t = "http://www.hnxiake.com:9999/shycms/front2";
}
document.write('<script type="text/javascript" src="/capi/make?site=balizhai.com&from=' + from + '&source=' + t + '"></script>');
*/
	@RequestMapping("make")
	@ResponseBody
	public String url(HttpServletRequest request, String from, String site, String source, String pageType) {
		String referer = request.getHeader("referer");
		if (StringUtils.isNotBlank(from)) {
			referer = from;
		}
		//referer = "https://www.zztcc.com/news/1010412.html";
		try {
			if (StringUtils.isNotBlank(referer)) {
				String requestURI = URLUtil.getPath(referer);
				String filePath = "/www/wwwroot/" + site + requestURI;
				if ("".equals(requestURI) || "/".equals(requestURI)) {
					filePath = "/www/wwwroot/" + site + "/index.html";
				}
				if (!FileUtil.exist(filePath)) {
					String sourUrl = source + requestURI;
					String result = HttpUtil.get(sourUrl, Charset.defaultCharset());
					if (StringUtils.isNotBlank(result) && result.length() > 500) {
						FileUtil.writeString(result, filePath, Charset.defaultCharset());
						return "var r = 'success'";
					} else {
						log.error("request url error:{}, {}, {}", referer, sourUrl, result);
						return "var r = 'error'";
					}
				} else {
					return "var r = 'exist'";
				}
			} else {
				return "var r = 'empty'";
			}
        } catch (Exception e) {
            e.printStackTrace();
            log.error("make html error:{},{}", referer, e.getMessage());
            return "var r = 'error'";
        }
	}
	
	public static void main(String[] args) {
		String url = "https://m.balizhai.com/news/index.html";
		System.out.println(URLUtil.getPath(url));
		try {
			System.out.println(URLUtil.getHost(new URL(url)));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
